import React,{Component} from "react";
import './css/page3.css'
import Header from "./components/Header";
import Content from "./components/Content";
import Footer from "./components/Footer";
export default class Page2 extends Component {
    constructor(){
        super();
        this.state={
            totalnum:0,
            totalprice:0,
            checkedAll:false,
            list:[{id:1,name:"商品一",price:100,num:1,checked:false},
            {id:2,name:"商品二",price:100,num:2,checked:false},
            {id:3,name:"商品三",price:100,num:3,checked:false},
            {id:4,name:"商品四",price:100,num:4,checked:false}
        ]
        }
    }
    calc=(id,num)=>{//这里增减数量
        this.setState({
            list:this.state.list.map((item)=>{
                if(item.id===id){
                    item.num+=num
                }
                return item
            })
        },()=>{this.totalnumAndPrice()})
    }
    
    delid=(id)=>{
        this.setState({
            list:this.state.list.filter(item=>item.id!==id)
        },()=>{this.checkCheckAll()})
    }
    setcheckall=(checked)=>{//全选
        this.setState({
            checkedAll:checked,
            list:this.state.list.map(info=>{
                info.checked= checked
                return info
            })
        },()=>{this.checkCheckAll()})
    }
    setcheckOne=(item,checked)=>{//单选
        this.setState({
            list:this.state.list.map(info=>{
                if(info.id===item.id){
                    info.checked=checked
                }
                return info
            })
        },()=>{this.checkCheckAll()})
    }
    checkCheckAll=()=>{//单选反选
        this.setState({
            checkedAll:this.state.list.length?
            this.state.list.every((item)=>item.checked):false
        },()=>{this.totalnumAndPrice()})
    }
    totalnumAndPrice=()=>{
        let num =0 ;
        let price = 0;
        let allcheck = this.state.list.filter(item=>item.checked);
        if(allcheck.length){
            allcheck.forEach(ele => {
                num += ele.num;
                price+=ele.price*ele.num
            });
        }
        this.setState({
           
            totalnum:num,
            totalprice:price
        })
    }
  render() {
    return (
      <>
      <div>Shoppingcar</div>
      <div className="table">
        <div className="tr">
        <Header checkedAll={this.state.checkedAll}
        setcheckall={this.setcheckall}
        ></Header>
       <Content list={this.state.list}
       setcheckOne={this.setcheckOne}
       delid={this.delid}
       calc={this.calc}
       ></Content>
        <Footer totalprice={this.state.totalprice}
        totalnum={this.state.totalnum}
        ></Footer>
        </div>
      </div>
      </>
    )
  }
}

